package xyz.ssf.cloud.project.system.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import xyz.ssf.cloud.common.core.storage.StorageFactory;
import xyz.ssf.cloud.common.core.storage.StorageStrategy;
import xyz.ssf.cloud.project.system.service.FileService;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 文件服务实现类
 * 
 * @author ssf
 */
@Service
public class FileServiceImpl implements FileService {
    
    private static final Logger log = LoggerFactory.getLogger(FileServiceImpl.class);

    @Autowired
    private StorageFactory storageFactory;

    /**
     * 上传文件
     * 
     * @param file 文件
     * @param directory 目录
     * @return 文件访问路径
     * @throws Exception 异常
     */
    @Override
    public String uploadFile(MultipartFile file, String directory) throws Exception {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("上传文件不能为空");
        }
        
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString().replace("-", "") + suffix;
        
        // 按日期生成目录
        String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        String path = directory + "/" + datePath;
        
        log.info("开始上传文件: {}/{}", path, filename);
        
        // 获取当前配置的存储策略
        StorageStrategy strategy = storageFactory.getStorageStrategy();
        log.info("当前使用的存储策略: {}", strategy.getType());
        
        try {
            // 使用存储策略上传文件
            String fileUrl = strategy.uploadFile(file, path, filename);
            log.info("文件上传成功: {}", fileUrl);
            return fileUrl;
        } catch (Exception e) {
            log.error("文件上传异常: {}", e.getMessage());
            throw new RuntimeException("文件上传异常: " + e.getMessage());
        }
    }

    /**
     * 删除文件
     * 
     * @param fileUrl 文件URL
     * @return 是否成功
     */
    @Override
    public boolean deleteFile(String fileUrl) {
        if (fileUrl == null || fileUrl.isEmpty()) {
            return false;
        }
        
        try {
            // 获取当前配置的存储策略
            StorageStrategy strategy = storageFactory.getStorageStrategy();
            log.info("使用存储策略 {} 删除文件: {}", strategy.getType(), fileUrl);
            
            // 使用存储策略删除文件
            return strategy.deleteFile(fileUrl);
        } catch (Exception e) {
            log.error("文件删除异常: {}", e.getMessage());
            return false;
        }
    }
}